package com.wenge.datagroup.storage.util

import com.alibaba.druid.pool.DruidDataSourceFactory

import javax.sql.DataSource

import java.util.Properties

/**
 * @author
 *   Depp
 */
class DruidDataSource(createDruidDataSource: () => DataSource) {
  lazy val dataSource: DataSource = createDruidDataSource()
}

object DruidDataSource {
  def apply(url: String, userName: String, password: String): DruidDataSource = {
    val createDataSourceFunc = () => {
      var dataSource: DataSource = null
      try {
        val props: Properties = getProps(url, userName, password)
        dataSource = DruidDataSourceFactory.createDataSource(props)
      } catch {
        case e: Exception =>
          e.printStackTrace()
      }
      dataSource
    }
    new DruidDataSource(createDataSourceFunc)
  }

  private def getProps(url: String, userName: String, password: String) = {
    val props = new Properties
    props.setProperty("url", url)
    props.setProperty("username", userName)
    props.setProperty("password", password)
    props.setProperty("initialSize", "5") // 初始化大小
    props.setProperty("maxActive", "50") // 最大连接
    props.setProperty("minIdle", "5") // 最小连接
    props.setProperty("maxWait", "60000") // 等待时长
    props.setProperty("timeBetweenEvictionRunsMillis", "2000") // 配置多久进行一次检测,检测需要关闭的连接 单位毫秒
    props.setProperty("minEvictableIdleTimeMillis", "600000") // 配置连接在连接池中最小生存时间 单位毫秒
    props.setProperty("maxEvictableIdleTimeMillis", "900000") // 配置连接在连接池中最大生存时间 单位毫秒
    props.setProperty("validationQuery", "select 1")
    props.setProperty("testWhileIdle", "true")
    props.setProperty("testOnBorrow", "false")
    props.setProperty("testOnReturn", "false")
    props.setProperty("keepAlive", "true")
    props.setProperty("phyMaxUseCount", "100000")
    props
  }
}
